<?php

namespace app\interfaces\controller;



use think\Db;

use think\Cache;

use think\Request;

use think\Exception;

use app\interfaces\model\Shop as ShopModel;

use app\interfaces\model\Coupon as CouponModel;

use app\interfaces\model\Limited as LimitedModel;

use app\interfaces\model\ShopHome as ShopHomeModel;

use app\interfaces\model\ShopGoods as ShopGoodsModel;

use app\interfaces\model\GroupGoods as GroupGoodsModel;

use app\interfaces\model\LimitedType as LimitedTypeModel;

use app\interfaces\model\MemberCollect as MemberCollectModel;

use app\interfaces\model\ShopGoodsType as ShopGoodsTypeModel;





class Shop

{

    /*

     * 用户端 - 前置方法

     */

    protected $beforeActionList = [

        'flow' => ['only' => 'top_find'],

    ];



    /*

     * 用户端 - 商品列表

     */

    public function shop_list()

    {



        // 获取参数

        $inquire = Request::instance()->param();

		$pagenum = isset($inquire['pagenum']) ? $inquire['pagenum'] : '1';

        // 搜索条件

        $condition['status'] = ['eq', 1];

        $condition['valid_time'] = [['gt', time()], ['eq', ''], 'or'];



        // 条件

        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];



        $model = new ShopModel();

        $result = $model->where($condition)

            ->field('member_id,title,m_banner banner,type,description,logo,collect_number')

            ->order(['sort' => 'desc', 'create_time' => 'desc'])

            ->paginate(5, false, ['query' => $inquire,'page' => $pagenum]);



        foreach ($result as $key => &$value) {

            $value->goods;

        }



        return ['code' => 200, 'message' => '成功', 'data' => $result];





    }



    /*

     * 用户端 - 店铺顶部

     * @param  string $user_id 唯一标示

     */

    public function top_find()

    {



        // 获取参数

        $user_id = Request::instance()->param('user_id', '0');

        $shop_id = Request::instance()->param('shop_id');



        if (empty($shop_id)) throw new Exception('not Empty');



        // 验证数据

        $result = ShopModel::where(['member_id' => $shop_id])->field('logo,m_banner banner,title,name,description,collect_number,phone,create_time,type')->find();

        $result['create_time'] = date('Y-m-d H:i:s', $result['create_time']);

        // 是否收藏

        $collect_state = (string)MemberCollectModel::where(['member_id' => $user_id, 'type_id' => '2', 'collect_id' => $shop_id])->value('id');



        if ($result) {

            return ['code' => 200, 'message' => '成功', 'data' => $result, 'collect_state' => $collect_state];

        }



        return ['code' => 401, 'message' => '网络繁忙'];



    }



    /*

     * 用户端 - 店铺分类

     * @param  string $user_id 唯一标示

     */

    public function shop_goods_list()

    {



        // 获取参数

        $user_id = Request::instance()->param('user_id');



        if (empty($user_id)) throw new Exception('not Empty');



        // 验证数据

        $result = ShopGoodsTypeModel::where(['member_id' => $user_id])->field('id,parenTid,title')->select();



        if ($result) {

            return ['code' => 200, 'message' => '成功', 'data' => recursion_node($result)];

        }



        return ['code' => 401, 'message' => '网络繁忙'];



    }



    /*

     * 用户端 - 店铺首页

     * @param  string $user_id 唯一标示

     */

    public function index_info()

    {



        // 获取参数

        $shop_id = Request::instance()->param('shop_id');

        // 获取当前分页
        
        $pagenum = Request::instance()->param('pagenum');

        $pagenum = isset($pagenum) ? $pagenum : '1';


        if (empty($shop_id)) throw new Exception('not Empty');



        self::flow($shop_id);



        // 验证数据

        $result = ShopHomeModel::where(['member_id' => $shop_id])->field('member_id', true)->find();

        $result['coupon'] = CouponModel::where(['member_id' => $shop_id, 'status' => '1', 'end_time' => ['gt', time()]])

            ->field('id,actual_price,virtual_price,number,sort as receive_status')

            ->order(['sort' => 'desc'])

            ->limit('3')

            ->select();



        $condition = ['member_id' => $shop_id, 'state' => '1'];



        // 是否开启审核

        if (Cache::get('web_commodity_audit') == 'Y') $condition['status'] = ['eq', '1'];



        $goods_list = ShopGoodsModel::where($condition)

            ->field('id,title,price,member_price,thumb_img,sale_number,rebate_percentage')

            ->order(['shop_sort' => 'desc', 'sort' => 'desc', 'create_time' => 'desc'])

            ->paginate(6, false, ['page' => $pagenum]);



        $limited_type = (new LimitedTypeModel())->where('id', 2)->value('end_time');





        foreach ($goods_list as &$value) {



            $limit_info = (new LimitedModel())->where('goods_id', $value['id'])->value('price');



            if ($limit_info && $limited_type['end_time'] > time() && $limited_type['start_time'] < time()) {



                if ($limit_info['purchase_number'] > $limit_info['number']) {



                    $value['price'] = $limit_info['price'];



                }





            }



            $special_price = (new GroupGoodsModel())->where(['goods_id' => $value['id'], 'status' => 1])->value('price');



            if ($special_price) {



                $value['price'] = $special_price;



            }



        }





        if ($result) {

            return ['code' => 200, 'message' => '成功', 'data' => $result, 'goods_list' => $goods_list];

        }



        return ['code' => 401, 'message' => '网络繁忙'];



    }



    /*

     * 用户端 - 全部商品列表 or 促销

     * @param  string $user_id 唯一标示

     */

    public function goods_list()

    {



        // 获取参数

        $inquire = Request::instance()->param();



        if (empty($inquire['user_id'])) throw new Exception('not Empty');



        // 搜索条件

        $condition['state'] = ['eq', 1];

        $condition['member_id'] = ['eq', $inquire['user_id']];



        // 是否开启审核

        if (Cache::get('web_commodity_audit') == 'Y') $condition['status'] = ['eq', '1'];



        // 条件

        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];

        if (!empty($inquire['parenTid'])) $condition['parentStr'] = ['like', '%,' . $inquire['parenTid'] . ',%'];

        if (!empty($inquire['promotion'])) $condition['promotion'] = ['eq', $inquire['promotion']];

        if (!empty($inquire['freight_type'])) $condition['freight_type'] = ['eq', '2'];

        if (!empty($inquire['low_price'])) $condition['price'] = ['egt', $inquire['low_price']];

        if (!empty($inquire['high_price'])) $condition['price'] = ['elt', $inquire['high_price']];

        if (!empty($inquire['low_price']) && $inquire['high_price']) $condition['price'] = [['egt', $inquire['low_price']], ['elt', $inquire['high_price']]];
        $pagenum = isset($inquire['pagenum']) ? $inquire['pagenum'] : '1';


        // 排序

        $sort = ['shop_sort' => 'desc', 'sort' => 'desc', 'create_time' => 'desc'];



        // 排序传参

        if (!empty($inquire['order'])) $sort = [$inquire['order'] => $inquire['rank']];



        $result = ShopGoodsModel::where($condition)->field('id,title,price,member_price,thumb_img,sale_number,rebate_percentage')

            ->order($sort)->paginate(10, false, ['query' => $inquire,'page' =>$pagenum]);





        return ['code' => 200, 'message' => '成功', 'data' => $result];





    }





    /*

     * 用户端 - 上新

     * @param  string $user_id 唯一标示

     */

    public function new_list()

    {



        // 获取参数

        $user_id = Request::instance()->param('user_id');



        if (empty($user_id)) throw new Exception('not Empty');



        $firstDay = date('Y-m-01', strtotime(date("Y-m-d")));               // 第一天

        $lastDay = date('Y-m-d', strtotime("$firstDay -3 month -1 day"));   // 最后一天



        // 搜索条件

        $condition['state'] = ['eq', 1];

        $condition['member_id'] = ['eq', $user_id];

        // $condition['date_time'] = ['between time', [$lastDay,$firstDay]];



        // 是否开启审核

        if (Cache::get('web_commodity_audit') == 'Y') $condition['status'] = ['eq', '1'];



        $result = ShopGoodsModel::where($condition)

            ->field('id,title,price,thumb_img,sale_number,rebate_percentage,date_time')

            ->order(['create_time' => 'desc'])->limit(10)

            ->select()->toArray();



        return ['code' => 200, 'message' => '成功', 'data' => arrayGrouping($result, 'date_time', 'date', 'list')];





    }



    /*

     * 用户端 - 取消收藏店铺

     * @param  string $id       店铺ID

     * @param  string $user_id  会员ID

     */

    public function collect_del()

    {



        $id = Request::instance()->param('id');

        $user_id = Request::instance()->param('user_id');



        if (empty($id) || empty($user_id)) throw new Exception('not Empty');





        // 取消收藏

        $result = MemberCollectModel::where(['collect_id' => $id, 'member_id' => $user_id])->delete();



        Db::name('Shop')->where('member_id',$id)->setDec('collect_number');



        if ($result) {

            return ['code' => 200, 'message' => '成功'];

        }



        return ['code' => 401, 'message' => '网络繁忙'];



    }



    public function flow($shop_id)



    {



        // 今日日期



        $hit_time = date('Y-m-d');







        $find = Db::name('shop_hit')->where(['shop_id'=>$shop_id,'hit_time'=>$hit_time])->find();







        if (empty($find)) {



            Db::name('shop_hit')->insert(['shop_id'=>$shop_id,'hit_time'=>$hit_time,'hits'=>1]);



        }else{



            Db::name('shop_hit')->where(['shop_id'=>$shop_id,'hit_time'=>$hit_time])->setInc('hits');



        }







    }





    /*

     * 用户端 - 增加访问量

     */



    // protected function create_volume($shop_id)

    // {

    //     $home_model = new ShopHomeModel();

    //

    //     $home_model->where(['member_id' => $shop_id])->setInc('visitor_volume', 1, 5);

    // }



}

